import React, { useState } from "react";
import {
  Form,
  Input,
  InputNumber,
  Switch,
  Slider,
  ColorPicker,
  Select,
  Button,
  Row,
  Col,
  Card,
  Divider,
  Spin,
  Tag,
  message,
  Empty,
  Typography,
} from "antd";
import {
  PlayCircleOutlined,
  LoadingOutlined,
  VideoCameraOutlined,
} from "@ant-design/icons";
import type { Color, ColorPickerProps } from "antd/es/color-picker";
import VideoMaterialSelector from "./VideoMaterialSelector";

const { Option, OptGroup } = Select;
const { Text } = Typography;

interface AnimationOption {
  name: string;
  display_name: string;
  is_vip: boolean;
  duration?: number;
  description: string;
}

interface AnimationData {
  intro_animations: AnimationOption[];
  outro_animations: AnimationOption[];
  loop_animations: AnimationOption[];
}

interface VideoMaterial {
  track_name: string;
  start_time: number;
  duration: number;
  relative_index: number;
  material: {
    path: string;
    name: string;
    crop_settings: any;
  };
}

interface ConfigDetailPanelProps {
  form: any;
  configType: string;
  configTitle: string;
  textColor: Color | string;
  borderColor: Color | string;
  backgroundColor: Color | string;
  introAnimation: string;
  outroAnimation: string;
  loopAnimation: string;
  animationData: AnimationData | null;
  loadingAnimations: boolean;
  videoMaterials: VideoMaterial[];
  onFormChange: (changedFields: any, allFields: any) => void;
  onTextColorChange: ColorPickerProps["onChange"];
  onBorderColorChange: ColorPickerProps["onChange"];
  onBackgroundColorChange: ColorPickerProps["onChange"];
  onIntroAnimationChange: (value: string) => void;
  onOutroAnimationChange: (value: string) => void;
  onLoopAnimationChange: (value: string) => void;
  onVideoMaterialsChange: (materials: VideoMaterial[]) => void;
  onScreenAdapt: () => void;
  // 新增自动保存回调
  onAutoSave?: () => void;
  textPosition: { x: number; y: number };
  onTextPositionChange: (position: { x: number; y: number }) => void;
}

const ConfigDetailPanel: React.FC<ConfigDetailPanelProps> = ({
  form,
  configType,
  configTitle,
  textColor,
  borderColor,
  backgroundColor,
  introAnimation,
  outroAnimation,
  loopAnimation,
  animationData,
  loadingAnimations,
  videoMaterials,
  onFormChange,
  onTextColorChange,
  onBorderColorChange,
  onBackgroundColorChange,
  onIntroAnimationChange,
  onOutroAnimationChange,
  onLoopAnimationChange,
  onVideoMaterialsChange,
  onScreenAdapt,
  onAutoSave,
  textPosition,
  onTextPositionChange,
}) => {
  // 视频素材相关函数 - 添加自动保存逻辑
  const updateVideoPath = (index: number, filePath: string) => {
    const updated = [...videoMaterials];
    updated[index] = {
      ...updated[index],
      material: {
        ...updated[index].material,
        path: filePath,
      },
    };

    if (
      filePath &&
      (!updated[index].material.name ||
        updated[index].material.name === "主背景视频" ||
        updated[index].material.name === `视频素材 ${index + 1}`)
    ) {
      const fileName =
        filePath.split("\\").pop() || filePath.split("/").pop() || filePath;
      updated[index].material.name = fileName.replace(/\.[^/.]+$/, "");
    }

    onVideoMaterialsChange(updated);
    // 触发自动保存
    if (onAutoSave) {
      setTimeout(onAutoSave, 100);
    }
  };

  const addVideoMaterial = () => {
    const newIndex = videoMaterials.length;
    const newMaterials = [
      ...videoMaterials,
      {
        track_name: `视频轨道 ${newIndex + 1}`,
        start_time: 2000000,
        duration: 4000000,
        relative_index: newIndex,
        material: {
          path: "",
          name: `视频素材 ${newIndex + 1}`,
          crop_settings: {
            upper_left_x: 0,
            upper_left_y: 0,
            upper_right_x: 1,
            upper_right_y: 0,
            lower_left_x: 0,
            lower_left_y: 1,
            lower_right_x: 1,
            lower_right_y: 1,
          },
        },
      },
    ];
    onVideoMaterialsChange(newMaterials);
    // 触发自动保存
    if (onAutoSave) {
      setTimeout(onAutoSave, 100);
    }
  };

  const removeVideoMaterial = (index: number) => {
    if (videoMaterials.length <= 1) {
      message.warning("至少需要保留一个视频素材");
      return;
    }

    const updated = videoMaterials.filter((_, i) => i !== index);
    // 重新设置relative_index
    updated.forEach((material, i) => {
      material.relative_index = i;
    });
    onVideoMaterialsChange(updated);
    // 触发自动保存
    if (onAutoSave) {
      setTimeout(onAutoSave, 100);
    }
  };

  const updateMaterialProperty = (
    index: number,
    property: string,
    value: any,
  ) => {
    const updated = [...videoMaterials];
    updated[index] = { ...updated[index], [property]: value };
    onVideoMaterialsChange(updated);
    // 触发自动保存
    if (onAutoSave) {
      setTimeout(onAutoSave, 100);
    }
  };

  const updateMaterialName = (index: number, name: string) => {
    const updated = [...videoMaterials];
    updated[index] = {
      ...updated[index],
      material: {
        ...updated[index].material,
        name: name || `视频素材 ${index + 1}`,
      },
    };
    onVideoMaterialsChange(updated);
    // 触发自动保存
    if (onAutoSave) {
      setTimeout(onAutoSave, 100);
    }
  };

  // 渲染动画选择器
  const renderAnimationSelect = (
    animations: AnimationOption[],
    value: string,
    onChange: (value: string) => void,
    placeholder: string,
  ) => {
    const freeAnimations = animations.filter((a) => !a.is_vip);
    const vipAnimations = animations.filter((a) => a.is_vip);

    return (
      <Select
        value={value}
        onChange={onChange}
        placeholder={placeholder}
        loading={loadingAnimations}
        style={{ width: "100%" }}
        optionLabelProp="label"
      >
        {freeAnimations.length > 0 && (
          <OptGroup label="免费动画">
            {freeAnimations.map((animation) => (
              <Option
                key={animation.name}
                value={animation.name}
                label={
                  <span>
                    {animation.display_name}
                    <Tag color="green" style={{ marginLeft: 4 }}>
                      免费
                    </Tag>
                  </span>
                }
              >
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                  }}
                >
                  <span>{animation.display_name}</span>
                  <Tag color="green">免费</Tag>
                </div>
              </Option>
            ))}
          </OptGroup>
        )}
        {vipAnimations.length > 0 && (
          <OptGroup label="付费动画">
            {vipAnimations.map((animation) => (
              <Option
                key={animation.name}
                value={animation.name}
                label={
                  <span>
                    {animation.display_name}
                    <Tag color="gold" style={{ marginLeft: 4 }}>
                      VIP
                    </Tag>
                  </span>
                }
              >
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    alignItems: "center",
                  }}
                >
                  <span>{animation.display_name}</span>
                  <Tag color="gold">VIP</Tag>
                </div>
              </Option>
            ))}
          </OptGroup>
        )}
      </Select>
    );
  };

  // 新增：视频素材选择器状态
  const [videoSelectorVisible, setVideoSelectorVisible] = useState(false);
  const [currentEditingIndex, setCurrentEditingIndex] = useState<number>(-1);

  // 新增：处理视频路径选择
  const handleVideoPathSelect = (filePath: string) => {
    if (currentEditingIndex >= 0) {
      updateVideoPath(currentEditingIndex, filePath);
    }
  };

  // 新增：打开视频选择器
  const openVideoSelector = (index: number) => {
    setCurrentEditingIndex(index);
    setVideoSelectorVisible(true);
  };

  // 根据不同的类型渲染配置内容
  const renderConfigContent = () => {

    // 当传入的configType为空时，显示提示信息
    if (!configType) {
      return (
        <div
          style={{
            height: "100%",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        >
          <Empty
            description="请在左侧选择要配置的项目"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        </div>
      );
    }

    // 如果是configType 处理 处理单个视频素材配置
    if (configType.startsWith("video-material-")) {
      const index = parseInt(configType.replace("video-material-", ""));
      const material = videoMaterials[index];

      if (!material) {
        return (
          <div
            style={{
              height: "100%",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <Empty
              description="视频素材不存在"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          </div>
        );
      }

      return (
        <div style={{ padding: "16px" }}>
          <Form.Item label="素材名称" required>
            <Input
              value={material.material.name}
              onChange={(e) => updateMaterialName(index, e.target.value)}
              placeholder="请输入素材名称"
            />
          </Form.Item>

          <Form.Item
            label="视频文件路径"
            required
            validateStatus={material.material.path ? "success" : "error"}
            help={material.material.path ? undefined : "请选择视频文件"}
          >
            <div
              style={{
                display: "flex",
                gap: "8px",
                alignItems: "flex-start",
                flexDirection: "column",
              }}
            >
              <Button
                type="primary"
                icon={<VideoCameraOutlined />}
                onClick={() => openVideoSelector(index)}
                style={{ width: "100%" }}
              >
                选择视频文件
              </Button>
              {material.material.path && (
                <div
                  style={{
                    padding: "8px 12px",
                    background: "#f6f8fa",
                    borderRadius: "4px",
                    fontSize: "12px",
                    color: "#666",
                    width: "100%",
                    wordBreak: "break-all",
                    border: "1px solid #e8e8e8",
                  }}
                >
                  <Text type="secondary">当前路径：</Text>
                  <Text copyable={{ text: material.material.path }}>
                    {material.material.path}
                  </Text>
                </div>
              )}
            </div>
          </Form.Item>

          <Form.Item label="轨道名称">
            <Input
              value={material.track_name}
              onChange={(e) =>
                updateMaterialProperty(index, "track_name", e.target.value)
              }
              placeholder="轨道名称"
            />
          </Form.Item>

          <Form.Item label="开始时间 (秒)">
            <InputNumber
              value={material.start_time / 1000000}
              onChange={(value) =>
                updateMaterialProperty(
                  index,
                  "start_time",
                  (value || 0) * 1000000,
                )
              }
              min={0}
              step={0.5}
              style={{ width: "100%" }}
            />
          </Form.Item>

          <Form.Item label="持续时间 (秒)">
            <InputNumber
              value={material.duration / 1000000}
              onChange={(value) =>
                updateMaterialProperty(
                  index,
                  "duration",
                  (value || 0) * 1000000,
                )
              }
              min={0.5}
              step={0.5}
              style={{ width: "100%" }}
            />
          </Form.Item>

          <Form.Item label="相对层级">
            <InputNumber
              value={material.relative_index}
              onChange={(value) =>
                updateMaterialProperty(index, "relative_index", value || 0)
              }
              min={0}
              style={{ width: "100%" }}
            />
          </Form.Item>

          <Divider />

          <div style={{ display: "flex", gap: "8px", flexWrap: "wrap" }}>
            <Button
              onClick={addVideoMaterial}
              style={{ flex: 1, minWidth: "120px" }}
            >
              添加新素材
            </Button>

            {videoMaterials.length > 1 && (
              <Button danger onClick={() => removeVideoMaterial(index)}>
                删除此素材
              </Button>
            )}
          </div>

          {/* 视频素材选择器 */}
          <VideoMaterialSelector
            visible={videoSelectorVisible}
            onClose={() => setVideoSelectorVisible(false)}
            onSelect={handleVideoPathSelect}
            currentPath={material.material.path}
          />
        </div>
      );
    }


    // 根据configType渲染不同的配置内容
    switch (configType) {
      

      // 如果是画布
      case "canvas":
        return (
          <Form form={form} layout="vertical" onFieldsChange={onFormChange}>
            <Form.Item label="宽度" name="canvasWidth">
              <InputNumber min={640} max={3840} style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item label="高度" name="canvasHeight">
              <InputNumber min={360} max={2160} style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item label="帧率" name="canvasFps">
              <InputNumber min={24} max={60} style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item>
              <Button
                icon={<PlayCircleOutlined />}
                onClick={onScreenAdapt}
                style={{ width: "100%" }}
              >
                适配当前屏幕
              </Button>
            </Form.Item>
          </Form>
        );

      case "text-basic":
        return (
          <Form form={form} layout="vertical" onFieldsChange={onFormChange}>
            <Form.Item label="文本内容" name="textContent">
              <Input.TextArea rows={3} />
            </Form.Item>
            <Form.Item label="开始时间 (秒)" name="textStartTime">
              <InputNumber min={0} step={0.1} style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item label="持续时间 (秒)" name="textDuration">
              <InputNumber min={0.5} step={0.5} style={{ width: "100%" }} />
            </Form.Item>

            {/* 添加位置控制 - 添加默认值保护 */}
            <Form.Item label="文本位置">
              <Row gutter={8}>
                <Col span={12}>
                  <InputNumber
                    addonBefore="X"
                    value={Math.round(textPosition?.x || 0)}
                    onChange={(value) =>
                      onTextPositionChange({
                        x: value || 0,
                        y: textPosition?.y || 0,
                      })
                    }
                    min={0}
                    style={{ width: "100%" }}
                  />
                </Col>
                <Col span={12}>
                  <InputNumber
                    addonBefore="Y"
                    value={Math.round(textPosition?.y || 0)}
                    onChange={(value) =>
                      onTextPositionChange({
                        x: textPosition?.x || 0,
                        y: value || 0,
                      })
                    }
                    min={0}
                    style={{ width: "100%" }}
                  />
                </Col>
              </Row>
              <div
                style={{
                  fontSize: "12px",
                  color: "#666",
                  marginTop: "4px",
                }}
              >
                💡 您也可以直接在预览区域拖拽文本来调整位置
              </div>
            </Form.Item>

            <Form.Item label="文本颜色">
              <ColorPicker value={textColor} onChange={onTextColorChange} />
            </Form.Item>
            <Form.Item label="字体大小" name="fontSize">
              <InputNumber min={4} max={72} style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item label="样式">
              <Row gutter={8}>
                <Col span={8}>
                  <Form.Item label="粗体" name="isBold" valuePropName="checked">
                    <Switch />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label="斜体"
                    name="isItalic"
                    valuePropName="checked"
                  >
                    <Switch />
                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label="下划线"
                    name="isUnderline"
                    valuePropName="checked"
                  >
                    <Switch />
                  </Form.Item>
                </Col>
              </Row>
            </Form.Item>
            <Form.Item label="透明度" name="textOpacity">
              <Slider min={0} max={1} step={0.01} />
            </Form.Item>
            <Form.Item label="对齐方式" name="textAlign">
              <Select>
                <Option value={0}>左对齐</Option>
                <Option value={1}>居中对齐</Option>
                <Option value={2}>右对齐</Option>
              </Select>
            </Form.Item>
            <Form.Item label="字间距" name="letterSpacing">
              <InputNumber min={0} max={50} style={{ width: "100%" }} />
            </Form.Item>
            <Form.Item label="行间距" name="lineSpacing">
              <InputNumber min={0} max={50} style={{ width: "100%" }} />
            </Form.Item>
          </Form>
        );

      case "text-border":
        return (
          <Form form={form} layout="vertical" onFieldsChange={onFormChange}>
            <Form.Item label="边框颜色">
              <ColorPicker value={borderColor} onChange={onBorderColorChange} />
            </Form.Item>
            <Form.Item label="边框透明度" name="borderOpacity">
              <Slider min={0} max={1} step={0.01} />
            </Form.Item>
            <Form.Item label="边框宽度" name="borderWidth">
              <InputNumber min={0} max={100} style={{ width: "100%" }} />
            </Form.Item>
          </Form>
        );

      case "text-background":
        return (
          <Form form={form} layout="vertical" onFieldsChange={onFormChange}>
            <Form.Item label="背景颜色">
              <ColorPicker
                value={backgroundColor}
                onChange={onBackgroundColorChange}
              />
            </Form.Item>
            <Form.Item label="背景样式" name="backgroundStyle">
              <Select>
                <Option value={0}>无背景</Option>
                <Option value={1}>矩形</Option>
                <Option value={2}>圆角矩形</Option>
                <Option value={3}>椭圆</Option>
              </Select>
            </Form.Item>
            <Form.Item label="背景透明度" name="backgroundOpacity">
              <Slider min={0} max={1} step={0.01} />
            </Form.Item>
            <Form.Item label="圆角半径" name="roundRadius">
              <Slider min={0} max={1} step={0.01} />
            </Form.Item>
            <Form.Item label="背景高度" name="backgroundHeight">
              <Slider min={0.1} max={1} step={0.01} />
            </Form.Item>
            <Form.Item label="背景宽度" name="backgroundWidth">
              <Slider min={0.1} max={1} step={0.01} />
            </Form.Item>
            <Form.Item label="水平偏移" name="horizontalOffset">
              <Slider min={0} max={1} step={0.01} />
            </Form.Item>
            <Form.Item label="垂直偏移" name="verticalOffset">
              <Slider min={0} max={1} step={0.01} />
            </Form.Item>
          </Form>
        );

      case "text-animation":
        return (
          <Form form={form} layout="vertical" onFieldsChange={onFormChange}>
            <Form.Item label="入场动画">
              {animationData ? (
                renderAnimationSelect(
                  animationData.intro_animations,
                  introAnimation,
                  onIntroAnimationChange,
                  "选择入场动画",
                )
              ) : (
                <Spin
                  indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />}
                />
              )}
            </Form.Item>
            <Form.Item label="入场持续时间 (秒)" name="introDuration">
              <InputNumber
                min={0.2}
                max={5}
                step={0.1}
                style={{ width: "100%" }}
              />
            </Form.Item>
            <Form.Item label="出场动画">
              {animationData ? (
                renderAnimationSelect(
                  animationData.outro_animations,
                  outroAnimation,
                  onOutroAnimationChange,
                  "选择出场动画",
                )
              ) : (
                <Spin
                  indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />}
                />
              )}
            </Form.Item>
            <Form.Item label="出场持续时间 (秒)" name="outroDuration">
              <InputNumber
                min={0.2}
                max={5}
                step={0.1}
                style={{ width: "100%" }}
              />
            </Form.Item>
            <Form.Item label="循环动画">
              {animationData ? (
                renderAnimationSelect(
                  animationData.loop_animations,
                  loopAnimation,
                  onLoopAnimationChange,
                  "选择循环动画",
                )
              ) : (
                <Spin
                  indicator={<LoadingOutlined style={{ fontSize: 24 }} spin />}
                />
              )}
            </Form.Item>
          </Form>
        );

      case "video-materials":
        return (
          <div style={{ padding: "16px" }}>
            <div style={{ marginBottom: "16px", textAlign: "center" }}>
              <Button
                type="dashed"
                onClick={addVideoMaterial}
                style={{ width: "100%" }}
              >
                添加视频素材
              </Button>
            </div>

            {videoMaterials.length === 0 ? (
              <Empty
                description="暂无视频素材，请添加"
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            ) : (
              <div>
                <h4>素材列表</h4>
                {videoMaterials.map((material, index) => (
                  <Card
                    key={index}
                    size="small"
                    title={material.material.name || `视频素材 ${index + 1}`}
                    style={{ marginBottom: "12px" }}
                  >
                    <p>
                      <strong>路径:</strong>{" "}
                      {material.material.path || "未设置"}
                    </p>
                    <p>
                      <strong>开始时间:</strong>{" "}
                      {(material.start_time / 1000000).toFixed(1)}秒
                    </p>
                    <p>
                      <strong>持续时间:</strong>{" "}
                      {(material.duration / 1000000).toFixed(1)}秒
                    </p>
                    <p>
                      <strong>层级:</strong> {material.relative_index}
                    </p>
                  </Card>
                ))}

                <div style={{ textAlign: "center", marginTop: "16px" }}>
                  <p style={{ color: "#666", fontSize: "12px" }}>
                    💡 点击左侧素材节点可以编辑单个素材
                  </p>
                </div>
              </div>
            )}
          </div>
        );

      default:
        return (
          <div
            style={{
              height: "100%",
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
            }}
          >
            <Empty
              description="配置项暂未实现"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          </div>
        );
    }
  };

  return (
    <Card
      title={configTitle || "详细配置"}
      headStyle={{
        color: "#fff",
        backgroundColor: "#705FBE",
        fontWeight: "bold",
        fontSize: "16px",
      }}
      size="small"
      style={{
        height: "100%",
        maxHeight: "100%", // 确保不超过父容器
        overflow: "hidden", // 防止Card本身溢出
      }}
      bodyStyle={{
        height: "calc(100% - 57px)",
        maxHeight: "calc(100% - 57px)", // 限制body高度
        overflow: "auto", // 内容可滚动
        padding: "16px",
      }}
    >
      {renderConfigContent()}
    </Card>
  );
};

export default ConfigDetailPanel;
